package com.dexcoder.demo.utils;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/**
 * Created by Administrator on 2017/06/01.
 */
public class MailUtils {

    private static Properties prop = null;

    // 定义发送邮箱的用户名
    private static String MAIL_USERNAME ;

    // 定义发送邮箱的密码
    private static String MAIL_PASSWORD;

    // 定义发送邮箱的主机信息
    private static String MAIL_HOST;

    // 定义发送邮件是否需要身份验证
    private static String MAIL_SMTP_AUTH;

    // 定义发送邮件的协议名称
    private static String MAIL_TRANSPORT_PROTOCOL;

    static{
        //加载发送邮件配置信息，并给相关的属性赋值
        loadConfig();
    }

    /**
     * 加载数据库配置信息，并给相关的属性赋值
     */
    public static void loadConfig() {
        try {
            InputStream inStream = JdbcUtils.class
                    .getResourceAsStream("/init.properties");
            prop = new Properties();
            prop.load(inStream);
            MAIL_USERNAME = prop.getProperty("mail.username");
            MAIL_PASSWORD = prop.getProperty("mail.password");
            MAIL_HOST= prop.getProperty("mail.host");
            MAIL_SMTP_AUTH = prop.getProperty("mail.smtp.auth");
            MAIL_TRANSPORT_PROTOCOL = prop.getProperty("mail.transport.protocol");
        } catch (Exception e) {
            throw new RuntimeException("读取邮件配置文件异常！", e);
        }
    }

    public MailUtils() {

    }

    /**
     * 获取邮件对象
     *
     * @return 邮件对象
     */
    public Session getSession() {
        // 设置环境信息
        Session session = Session.getInstance(prop);
        return session;
    }

    /**
     * 获取Transport
     *
     * @return Transport
     */
    public Transport getTransport(Session session) {
        Transport transport = null;
        try {
            transport = session.getTransport();
            transport.connect(MAIL_USERNAME, MAIL_PASSWORD);
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return transport;
    }

}
